package com.thesharegame.dal.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.thesharegame.dal.search.SQLGenerator;
import com.thesharegame.dal.search.SQLGeneratorFactory;
import com.thesharegame.dal.util.HibernateUtil;

public abstract class AbstractDAO<T> implements DataAccessObject<T>{

	@Override
	public boolean save(T object){
		SessionFactory factory = HibernateUtil.getSessionFactory();
		
		Session session = factory.getCurrentSession();
		session.beginTransaction();
        session.save(object);
        session.getTransaction().commit();
        
		return true;
	}

	public boolean delete(T object){
		SessionFactory factory = HibernateUtil.getSessionFactory();
		
		Session session = factory.getCurrentSession();
		session.beginTransaction();
		session.delete(object);
		session.getTransaction().commit();
		
		return true;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<T> find(T prototype) {
		SQLGeneratorFactory factory = SQLGeneratorFactory.getInstance();
		SQLGenerator generator = factory.createGenerator(prototype);
		String hql = generator.getSQL(prototype);
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Query query = session.createQuery(hql);
		List<T> results = query.list();
		session.getTransaction().commit();

		return results;
	}
	
	@Override
	public boolean update(T object) {
		SessionFactory factory = HibernateUtil.getSessionFactory();
		
		Session session = factory.getCurrentSession();
		session.beginTransaction();
		session.update(object);
		session.getTransaction().commit();
		
		return true;
	}
}
